//
//  HJPictureView.swift
//  HJWeiBo
//
//  Created by 黄珏 on 15/11/1.
//  Copyright © 2015年 黄珏. All rights reserved.
//

import UIKit
import SDWebImage

class HJPictureView: UICollectionView {
    
    private let StatusPictureViewIdentifier = "StatusPictureViewIdentifier"
    
    var status: HJStatus? {
        didSet{
//            调用sizeThatFits方法
            sizeToFit()
        }
    }
    
    //MARK:构造方法
    let layout = UICollectionViewFlowLayout()
    init() {
//        frame先给0，因为后面有约束   必须要有collectionViewLayout: layout这个属性
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor.clearColor()
        dataSource = self
        registerClass(HJStatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calViewSize()
    }
    
    func calViewSize() -> CGSize {
        
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        let itemSize = CGSizeMake(90, 90)
        layout.itemSize = itemSize
        let margin = CGFloat(10)
//        获取图片数量
        let count = status!.pictureURLs?.count ?? 0
//        列数
        let colnum = 3
//        特殊处理
        if count == 0 {
            return CGSizeZero
        }
        if count == 1 {
//            layout.itemSize = CGSizeMake(150,120)
//            return CGSizeMake(150, 120)
            if count == 1 {
                // 获取图片url地址
                let urlString = status!.pictureURLs![0].absoluteString
                
                var size = CGSize(width: 150, height: 120)
                
                // 获取图片, 有图片设置size为图片的size,如果没有图片使用默认的
                if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString) {
                    size = image.size
                }
                
                // 有些图片宽度很小
                if size.width < 40 {
                    size.width = 40
                }
                
                layout.itemSize = size
                return size
            }
        }
        if count == 4 {
            return CGSizeMake(itemSize.width * 2 + margin, itemSize.width * 2 + margin)
        }
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        // 计算行数: 公式: 行数 = (图片数量 + 列数 -1) / 列数
        let row = (count + colnum - 1) / colnum
        
        // 宽度公式: 宽度 = (列数 * item的宽度) + (列数 - 1) * 间距
        let widht = (CGFloat(colnum) * itemSize.width) + (CGFloat(colnum) - 1) * margin
        
        // 高度公式: 高度 = (行数 * item的高度) + (行数 - 1) * 间距
        let height = (CGFloat(row) * itemSize.height) + (CGFloat(row) - 1) * margin
        
        return CGSizeMake(widht, height)
    }
}

extension HJPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewIdentifier, forIndexPath: indexPath) as! HJStatusPictureViewCell
        cell.imageURL = status?.pictureURLs?[indexPath.item]
        return cell
    }
}

class HJStatusPictureViewCell: UICollectionViewCell {
//    一开始是空 赋值后（didSet）给iconview赋值
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func prepareUI() {
        contentView.addSubview(iconView)
        iconView.ff_Fill(contentView)
    }
//    懒加载
    private lazy var iconView: UIImageView = {
    let imageView = UIImageView()
    
    // 设置内容模式
    imageView.contentMode = UIViewContentMode.ScaleAspectFill
    
    imageView.clipsToBounds = true
    
    return imageView
    }()
}